package com.jdcjk.project.account.view;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.jdcjk.R;
import com.jdcjk.UrlAddress;
import com.jdcjk.base.presenter.BasePresenter;
import com.jdcjk.base.view.BaseFragment;
import com.jdcjk.project.account.model.entity.AddressInfo;
import com.jdcjk.project.account.model.entity.Result;
import com.jdcjk.project.account.presenter.RegisteredPresenter;
import com.jdcjk.util.L;
import com.jdcjk.util.dtr.zxing.AddressInfoUtis;

import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Request;

import static com.jdcjk.R.id.back_btn;

/**
 * Created by Administrator on 2016/12/14 0014.
 */

public class RegisteredFragment extends BaseFragment<RegisteredPresenter> {
    private final String TAG = RegisteredFragment.class.getSimpleName();
    //返回Button
    private ImageButton back_button;
    //顶栏标题
    private TextView barTitle_textview;
    //用户名称EditText
    private EditText registeredName_editText;
    //验证码EditText
    private EditText registeredVerificationCode_editText;
    //手机号EditText
    private EditText registeredPhone_editText;
    //密码EditText
    private EditText registeredPwd_editText;
    //获取验证码TextView
    private TextView verificationCode_textView;
    //邮箱EditText
    private EditText registeredEmail_editText;
    //地址EditText
    private TextView registeredAddress_textview;
    //注册Button
    private Button registered_button;
    //取消Button
    private Button cancle_button;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_registered;
    }

    @Override
    public RegisteredPresenter bindPresenter() {
        presenter = new RegisteredPresenter(getContext());
        return presenter;
    }

    @Override
    public void initContentView(View viewContent) {
        //初始化控件
        back_button = (ImageButton) viewContent.findViewById(back_btn);
        back_button.setOnClickListener(this);
        barTitle_textview = (TextView) viewContent.findViewById(R.id.bar_title_textview);
        barTitle_textview.setText(R.string.registered);
        registeredName_editText = (EditText) viewContent.findViewById(R.id.registered_name_et);
        registeredPhone_editText = (EditText) viewContent.findViewById(R.id.registered_phone_et);
        registeredVerificationCode_editText = (EditText) viewContent.findViewById(R.id.registered_verification_code_et);
        verificationCode_textView = (TextView) viewContent.findViewById(R.id.verification_code_tv);
        verificationCode_textView.setOnClickListener(this);
        registeredPwd_editText = (EditText) viewContent.findViewById(R.id.registered_pwd_et);
        registeredEmail_editText = (EditText) viewContent.findViewById(R.id.registered_email_et);
        registeredAddress_textview = (TextView) viewContent.findViewById(R.id.registered_address_tv);
        registeredAddress_textview.setOnClickListener(this);
        registered_button = (Button) viewContent.findViewById(R.id.fragment_registered_btn);
        registered_button.setOnClickListener(this);
        cancle_button = (Button) viewContent.findViewById(R.id.fragment_cancle_btn);
        cancle_button.setOnClickListener(this);
    }

    /**
     * 注册
     */
    public void register() {
        String name = registeredName_editText.getText().toString();
        String phone = registeredPhone_editText.getText().toString();
        String pwd = registeredPwd_editText.getText().toString();
        String verificationCode = registeredVerificationCode_editText.getText().toString();
        String email = registeredEmail_editText.getText().toString();
        String address = registeredAddress_textview.getText().toString();
        //判断必要项是不是未输入
        if (verificationCode.length() != 6) {
            Toast.makeText(getActivity(), "请填写正确6位验证码", Toast.LENGTH_SHORT).show();
        }
        if (!name.equals("") && !phone.equals("") && !pwd.equals("")) {
            //注册网络请求
            presenter.registered(UrlAddress.REGISTER, phone, pwd, verificationCode, name, email, address, new BasePresenter.OnUIThreadListener<Result>() {
                @Override
                public void onBefore(Request request, int id) {
                    registered_button.setClickable(false);
                }

                @Override
                public void onAfter(int id) {

                }

                @Override
                public void onError(Call call, Exception e, int i) {
                    L.i(TAG, "onError:e " + e);
                }

                @Override
                public void onResponse(Result result) {
                    if (result.getStatus().equals("OK")) {
                        Message msg = new Message();
                        msg.what = 11;
                        handler.sendMessage(msg);
                        getActivity().finish();
                    } else {
                        Toast.makeText(getActivity(), result.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                    registered_button.setClickable(true);
                }
            });
        } else {
            Toast.makeText(getActivity(), "带*的项目必须填写", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 获得验证码
     */
    public void getVerificationCode() {
        String phone = registeredPhone_editText.getText().toString();
        if (phone.equals("") || phone.trim().length() != 11) {
            Toast.makeText(getActivity(), "请填写正确的11位手机号码", Toast.LENGTH_SHORT).show();
            return;
        }
        final Message msg = new Message();
        //获取验证码
        presenter.getVerificationCode(UrlAddress.GET_CODE, phone, "SMS_7395039", new BasePresenter.OnUIThreadListener<Result>() {

            @Override
            public void onBefore(Request request, int id) {

            }

            @Override
            public void onAfter(int id) {

            }

            @Override
            public void onError(Call call, Exception e, int i) {
                msg.what = 7;
                handler.sendMessage(msg);
            }

            @Override
            public void onResponse(Result result) {
                if (result.getStatus().equals("OK")) {
                    msg.what = 1;
                    verificationCode_textView.setClickable(false);
                    handler.sendMessage(msg);
                } else if (result.getStatus().equals("ALREADY_EXIST")) {
                    msg.what = 11;
                    handler.sendMessage(msg);
                } else if (result.getStatus().equals("FAILED")) {
                    msg.what = 6;
                    handler.sendMessage(msg);
                } else if (result.getStatus().equals("SYS_ERROR")) {
                    msg.what = 7;
                    handler.sendMessage(msg);
                }
            }


        });
    }

    //验证码返回值判断handler
    private int number = 60;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (number == 0) {
                        verificationCode_textView.setTextSize((float) 15);
                        verificationCode_textView.setText("获取验证码");
                        verificationCode_textView.setClickable(true);
                        number = 60;
                    } else {
                        verificationCode_textView.setTextSize((float) 20);
                        verificationCode_textView.setText(number + "s");
                        number--;
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Message msg = new Message();
                                msg.what = 1;
                                handler.sendMessage(msg);
                            }
                        }, 1000);
                    }
                    break;
                case 11:
                    Toast.makeText(getActivity(), R.string.user_is_exist, Toast.LENGTH_SHORT).show();
                    break;
                case 10:
                    Toast.makeText(getActivity(), R.string.registered_succes, Toast.LENGTH_SHORT).show();
                    break;
                case 6:
                    Toast.makeText(getActivity(), R.string.send_verification_code_fail, Toast.LENGTH_SHORT).show();
                    break;
                case 7:
                    Toast.makeText(getActivity(), R.string.system_exception, Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    /**
     * *********************************************设置地址*********************************************
     */

    private AddressPopupWindow addressPopupWindow;
    private String provinceName;
    private String cityName;
    private String areaName;
    private ArrayList<AddressInfo> addressInfoList;
    //地址类型
    private AddressInfoUtis.AddressType addressType;


    public void choiceAddress() {
        addressInfoList = AddressInfoUtis.getProvinceInfo(getActivity());
        addressType = AddressInfoUtis.AddressType.getFromString(AddressInfoUtis.AddressType.PROVINCE.toString());
        showAddressPopuwindow(addressType, addressInfoList);
    }

    /**
     * 弹出地址选择器
     *
     * @param addressType  地址类型
     * @param addressInfos 区域信息列表
     */
    private void showAddressPopuwindow(AddressInfoUtis.AddressType addressType, ArrayList<AddressInfo> addressInfos) {
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = 0.5f;
        getActivity().getWindow().setAttributes(lp);//改变背景颜色
        addressPopupWindow = new AddressPopupWindow(getActivity(), addressType, itemsOnClick, addressInfos);
        addressPopupWindow.showAtLocation(getActivity().findViewById(R.id.fragment_registered_ll), Gravity.CENTER, 0, 0);
        addressPopupWindow.update();
        addressPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                lp.alpha = 1f;//恢复背景颜色
                getActivity().getWindow().setAttributes(lp);
            }
        });
    }

    // PopupWindow弹出窗体的实现监听类
    private AdapterView.OnItemClickListener itemsOnClick = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (addressType == AddressInfoUtis.AddressType.PROVINCE) {
                String provinceCode = ((AddressInfo) parent.getItemAtPosition(position)).getProvinceCode();
                provinceName = ((AddressInfo) parent.getItemAtPosition(position)).getName();
                addressPopupWindow.dismiss();
                addressInfoList = AddressInfoUtis.getCityInfo(getActivity(), provinceCode);
                addressType = AddressInfoUtis.AddressType.getFromString(AddressInfoUtis.AddressType.CITY.toString());
                showAddressPopuwindow(addressType, addressInfoList);
            } else if (addressType == AddressInfoUtis.AddressType.CITY) {
                String cityCode = ((AddressInfo) parent.getItemAtPosition(position)).getProvinceCode();
                cityName = ((AddressInfo) parent.getItemAtPosition(position)).getName();
                addressPopupWindow.dismiss();
                addressInfoList = AddressInfoUtis.getAreaInfo(getActivity(), cityCode);
                addressType = AddressInfoUtis.AddressType.getFromString(AddressInfoUtis.AddressType.AREA.toString());
                showAddressPopuwindow(addressType, addressInfoList);
            } else if (addressType == AddressInfoUtis.AddressType.AREA) {
                areaName = ((AddressInfo) parent.getItemAtPosition(position)).getName();
                addressPopupWindow.dismiss();
                registeredAddress_textview.setTextColor(getResources().getColor(R.color.black));
                if (provinceName.equals(cityName) && !cityName.equals(areaName)) {
                    registeredAddress_textview.setText(cityName + "-" + areaName);
                } else if (!provinceName.equals(cityName) && cityName.equals(areaName)) {
                    registeredAddress_textview.setText(provinceName + "-" + cityName);
                } else if (provinceName.equals(cityName) && cityName.equals(areaName)) {
                    registeredAddress_textview.setText(areaName);
                } else {
                    registeredAddress_textview.setText(provinceName + "-" + cityName + "-" + areaName);
                }
            }
        }
    };

}
